<!-- GoodsEditDialog.vue -->
<template>
    <el-dialog v-model="dialogVisible" title="编辑商品信息" width="50%" :before-close="handleClose">
        <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
            <el-form-item label="商品ID" prop="goods_id">
                <el-input v-model="form.goods_id" />
            </el-form-item>
            <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="form.goods_name" />
            </el-form-item>
            <el-form-item label="商品库存" prop="inventory">
                <el-input-number v-model="form.inventory" :min="0" />
            </el-form-item>
            <el-form-item label="销售量" prop="sale_volume">
                <el-input-number v-model="form.sale_volume" :min="0" />
            </el-form-item>
            <el-form-item label="创建时间">
                <el-input v-model="form.create_time" disabled />
            </el-form-item>
            <el-form-item label="封面图" prop="cover">
                <el-input v-model="form.cover" />
                <!-- 可以添加图片上传组件 -->
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
                <el-input-number v-model="form.price" :min="0" :precision="2" :step="0.01" />
            </el-form-item>
            <el-form-item label="所属店铺ID" prop="owner_store_id">
                <el-input v-model="form.owner_store_id" />
            </el-form-item>
            <el-form-item label="是否推荐" prop="recommend">
                <el-switch v-model="form.recommend" />
            </el-form-item>
            <el-form-item label="商品类型" prop="type">
                <el-input v-model="form.type" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
                <el-input-number v-model="form.sort" :min="0" />
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import axios from "../../public/request"

const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
    goodsData: {
        type: Object,
        default: () => ({})
    }
})

const emit = defineEmits(['update:visible', 'success'])

const dialogVisible = ref(props.visible)
const formRef = ref(null)

// 表单数据
const form = reactive({
    id: 0,
    goods_id: '',
    goods_name: '',
    inventory: 0,
    sale_volume: 0,
    create_time: '',
    cover: '',
    price: 0,
    owner_store_id: '',
    recommend: false,
    type: '',
    sort: 0
})

// 表单验证规则
const rules = {
    goods_id: [{ required: true, message: '请输入商品ID', trigger: 'blur' }],
    goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
    inventory: [{ required: true, message: '请输入库存数量', trigger: 'blur' }],
    price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
    owner_store_id: [{ required: true, message: '请输入所属店铺ID', trigger: 'blur' }],
    type: [{ required: true, message: '请输入商品类型', trigger: 'blur' }]
}

// 监听对话框可见性变化
watch(() => props.visible, (val) => {
    dialogVisible.value = val
})

// 监听对话框内部可见性变化
watch(dialogVisible, (val) => {
    emit('update:visible', val)
})

// 监听商品数据变化，填充表单
watch(() => props.goodsData, (val) => {
    if (val && Object.keys(val).length > 0) {
        Object.keys(form).forEach(key => {
            if (key in val) {
                form[key] = val[key]
            }
        })
    }
}, { immediate: true, deep: true })

// 关闭对话框
const handleClose = () => {
    dialogVisible.value = false
}

// 提交表单
const submitForm = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid, fields) => {
        if (valid) {
            try {
                // 发送请求保存数据
                console.log("修改的商品数据:", form);
                const res  = await axios.put("/goodsManage/updateGoods", form);
                afterHandle(res);
                
            } catch (error) {
                console.error('保存商品信息时出错:', error)
                ElMessage({
                    type: 'error',
                    message: '网络错误，请稍后重试'
                })
            }
        } else {
            console.log('表单验证失败', fields)
        }
    })
}

// 处理保存后的操作
const afterHandle = (res) => {
    if (res.data.code === 1) {
        ElMessage.success("商品信息保存成功");
        handleClose()
        emit('success')
    } else {
        ElMessage({
            type: 'error',
            message: res.data.msg || '保存失败，请稍后重试'
        })
    }
}
</script>

<style scoped>
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>